#!/usr/bin/python

#
# Copyright 2007 Luciano Xumerle. All rights reserved.
# Luciano Xumerle <luciano.xumerle@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import os
import sys
import replaces
import CDDB
import XFile
from optparse import OptionParser


def doMsg():
	version = '3.0.0beta2'
	date = 'December 8, 2007'
	r1 = "cnxrename version " + version + " (" + date + ")"
	r2 = "Copyright 2007 by Luciano Xumerle <luciano.xumerle@gmail.com>"
	r3 = "This is free software; see the source for copying conditions. There is NO"
	r4 = "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
	r5 = "[-h] : Print help."
	r0 = '-' * len(r4)
	sys.stderr.write( "\n".join([r0,r1,r2,r3,r4,r5,r0]) + "\n")

def writeOKmessage():
	sys.stderr.write( " OK. LIST IS EMPTY\n" )


def doTest( lnt, listXFile ):
	"""
	"""
	fileOK = True
	print "\n== List of files with length > " + str(lnt) + " chars =="
	for i in range(len(listXFile)):
		name = listXFile[ i ].getDest() + listXFile[ i ].getExtension()
		ll = len(name)
		if ll > lnt:
			fileOK = False
			print " - " + len(ll) + ": " + name + "\n"
	if fileOK:
		writeOKmessage()
	print
	return

def doTXTopt( txt, printAuthor, recursive, selectDir, extension, match, noMatch ):
	renamer=replaces.Renamer('.', recursive, selectDir, extension, match, noMatch)
	if renamer.fromCDDB( txt, printAuthor ):		
		print "== Multimedia File renamed from CDDB file ==\n"
		renamer.executeRename()
	else:
		print "\n== ERROR processing CDDB file ==\n" + NOFILERENAME


def doM3Uopt( m3u ):
	listXFile=[]
	fout = open(m3u, "a")
	counter = 1
	for line in open(m3u, "r"):
		process = line.lstrip().rstrip()
		if os.path.isfile(process):
			if process == "" or process == '#':
				continue
			xfile = XFile.XFile(process, False)
			prefixed = str(counter) + '-' + xfile.getDest()
			if counter < 10:
				prefixed = "0" + prefixed
			xfile.setDest(prefixed)
			listXFile.append(xfile)
			counter+=1
	return listXFile

def doCUE( txt, match, noMatch ):
	# get the wav file list
	files = replaces.fileList( '.', False, False, 'wav', match, noMatch )
	# read the txt
	cddb = CDDB.CDDB( txt, False )
	if not cddb.printCUE(files):
		print "\n== ERROR with number of CDDB songs number and number of wav files =="
	return


def main():
	"""main routine"""

	CDDBerror = "\n## ERROR processing CDDB file ##\n"

	renamer = replaces.Renamer( '.', sys.argv[1:] )
	if not renamer.parseParameters():
		print "Parse error: wrong input parameter.\n"
		return

	options=renamer.getOptions()

	# write message
	if options.verbose:
		doMsg()

	# cue option activated
	cuefile=options.cue and os.path.isfile(options.cue)

	# check cddb
	cddb = options.filetxt and os.path.isfile(options.filetxt)
	if cddb:
		print "== Multimedia File renamed from CDDB file ==\n"
		

	# apply parameter
	torename=renamer.applyParameters()

	# do renaming
	if len(torename)>0:
		for i in range(len(torename)):
			print torename[i].toString()

		ppp = "no"
		if options.test:
			for i in range(len(torename)):
				print torename[ i ].getDestFile()
		elif options.auto:
			ppp="yes"
		else:
			print "== print [yes] to rename files or [help] to show help =="
			print "--> ",
			ppp=sys.stdin.readline()
	
		if ppp.strip()=="yes":
			for i in range(len(torename)):
				if not torename[i].renameFile():
					print "Unable to rename the file: " + torename[i].getFile()
	else:
		if cuefile and not renamer.getStatus():
			print CDDBerror
		if cddb and not renamer.getStatus():
			print CDDBerror

	# check file length
	badfile=[]
	if options.fileLength:
		badfile=renamer.doTest( 64 )
	elif options.fileLength103:
		badfile=renamer.doTest( 103 )
	if len(badfile)==0:
		writeOKmessage()
	else:
		print "\n== List of files with invalid length =="
		for i in range(len(badfile)):
			print " - " + str(len(badfile[i])) + ": " + badfile[i] + "\n"

if __name__=='__main__': main()

